<template>
  <div class="daily-record">
    <van-nav-bar
      title="录入健康数据"
      left-arrow
      @click-left="router.back()"
    />

    <van-form @submit="handleSubmit">
      <!-- 记录类型选择 -->
      <van-cell-group inset title="选择记录类型">
        <van-cell
          v-for="type in recordTypes"
          :key="type.value"
          :title="type.label"
          clickable
          @click="form.recordType = type.value"
        >
          <template #right-icon>
            <van-radio :name="type.value" v-model="form.recordType" />
          </template>
        </van-cell>
      </van-cell-group>

      <!-- 血压录入 -->
      <van-cell-group
        inset
        title="血压数值"
        v-if="form.recordType === 1"
      >
        <van-field
          v-model="form.systolic"
          type="number"
          label="收缩压"
          placeholder="请输入收缩压"
          :rules="[{ required: true, message: '请输入收缩压' }]"
        >
          <template #right-icon>mmHg</template>
        </van-field>
        <van-field
          v-model="form.diastolic"
          type="number"
          label="舒张压"
          placeholder="请输入舒张压"
          :rules="[{ required: true, message: '请输入舒张压' }]"
        >
          <template #right-icon>mmHg</template>
        </van-field>
      </van-cell-group>

      <!-- 其他类型数值录入 -->
      <van-cell-group
        inset
        title="测量数值"
        v-else
      >
        <van-field
          v-model="form.recordValue"
          type="number"
          :label="getValueLabel"
          :placeholder="getValuePlaceholder"
          :rules="[{ required: true, message: '请输入数值' }]"
        >
          <template #right-icon>{{ getValueUnit }}</template>
        </van-field>
      </van-cell-group>

      <!-- 测量时间 -->
      <van-cell-group inset title="测量时间">
        <van-field
          v-model="formattedTime"
          readonly
          label="时间"
          placeholder="请选择测量时间"
          @click="showTimePicker = true"
        >
          <template #right-icon>
            <van-icon name="clock-o" />
          </template>
        </van-field>
      </van-cell-group>

      <!-- 备注信息 -->
      <van-cell-group inset title="备注">
        <van-field
          v-model="form.remark"
          type="textarea"
          placeholder="请输入备注信息"
          rows="2"
          autosize
        />
      </van-cell-group>

      <div style="margin: 16px;">
        <van-button round block type="primary" native-type="submit">
          提交
        </van-button>
      </div>
    </van-form>

    <!-- 时间选择器 -->
    <van-popup
      v-model:show="showTimePicker"
      position="bottom"
    >
      <van-datetime-picker
        v-model="form.measureTime"
        type="datetime"
        title="选择时间"
        :max-date="new Date()"
        @confirm="onTimeConfirm"
        @cancel="showTimePicker = false"
      />
    </van-popup>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'
import { addHealthRecord } from '@/api/health'
import dayjs from 'dayjs'

const router = useRouter()
const showTimePicker = ref(false)

// 记录类型列表
const recordTypes = [
  { label: '血压', value: 1 },
  { label: '血糖', value: 2 },
  { label: '体重', value: 3 },
  { label: '体温', value: 4 }
]

const form = ref({
  recordType: null,
  systolic: '',
  diastolic: '',
  recordValue: '',
  measureTime: new Date(),
  remark: ''
})

// 计算属性
const getValueLabel = computed(() => {
  switch (form.value.recordType) {
    case 2: return '血糖值'
    case 3: return '体重'
    case 4: return '体温'
    default: return '数值'
  }
})

const getValuePlaceholder = computed(() => {
  switch (form.value.recordType) {
    case 2: return '请输入血糖值'
    case 3: return '请输入体重'
    case 4: return '请输入体温'
    default: return '请输入数值'
  }
})

const getValueUnit = computed(() => {
  switch (form.value.recordType) {
    case 2: return 'mmol/L'
    case 3: return 'kg'
    case 4: return '℃'
    default: return ''
  }
})

const formattedTime = computed(() => {
  return dayjs(form.value.measureTime).format('YYYY-MM-DD HH:mm')
})

// 时间确认
const onTimeConfirm = (value) => {
  form.value.measureTime = value
  showTimePicker.value = false
}

// 提交记录
const handleSubmit = async () => {
  try {
    let recordData = {
      recordType: form.value.recordType,
      measureTime: form.value.measureTime,
      remark: form.value.remark
    }

    // 处理不同类型的数值
    if (form.value.recordType === 1) {
      // 血压数据
      if (!form.value.systolic || !form.value.diastolic) {
        showToast('请输入完整的血压数据')
        return
      }
      // 血压数据验证
      const systolic = parseFloat(form.value.systolic)
      const diastolic = parseFloat(form.value.diastolic)

      if (systolic < 60 || systolic > 200) {
        showToast('收缩压范围应在60-200之间')
        return
      }
      if (diastolic < 40 || diastolic > 130) {
        showToast('舒张压范围应在40-130之间')
        return
      }
      recordData.recordValue = `${systolic}/${diastolic}`
    } else {
      // 其他类型数据
      if (!form.value.recordValue) {
        showToast('请输入数值')
        return
      }
      const value = parseFloat(form.value.recordValue)

      // 数值验证
      switch (form.value.recordType) {
        case 2: // 血糖
          if (value < 0 || value > 30) {
            showToast('血糖值范围应在0-30之间')
            return
          }
          break
        case 3: // 体重
          if (value < 20 || value > 200) {
            showToast('体重范围应在20-200之间')
            return
          }
          break
      }
      recordData.recordValue = value.toFixed(1) // 保留一位小数
    }

    await addHealthRecord(recordData)
    showToast('添加成功')
    router.back()
  } catch (error) {
    console.error('添加失败:', error)
    showToast('添加失败')
  }
}
</script>

<style lang="scss" scoped>
.daily-record {
  min-height: 100vh;
  background-color: #f7f8fa;
  padding-bottom: 20px;

  :deep(.van-cell-group) {
    margin-top: 12px;
  }

  :deep(.van-field__right-icon) {
    color: #666;
  }

  :deep(.van-radio) {
    margin-right: 0;
  }
}
</style>
